package com.ciklum.robotester;

import org.opencv.core.*;
import org.opencv.highgui.Highgui;
import org.opencv.imgproc.Imgproc;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

/**
 * Created by miy on 7/4/2014.
 */
class ImageMatcher {
    private final Robot robot;
    private ThreadLocal<Double> throughput = new InheritableThreadLocal<Double>();

    ImageMatcher(Robot robot) {
        this.robot = robot;
        System.loadLibrary("opencv_java249");
    }

    BufferedImage captureScreen() {
        Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
        BufferedImage capture = null;
        capture = robot.createScreenCapture(screenRect);
        return capture;
    }

    File getFile(BufferedImage bufferedImage)  {
        File file =  new File(System.getProperty("java.io.tmpdir")+"temp.png");
        try {
            ImageIO.write(bufferedImage, "png",file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;


    }

    Point find(File templateFile) {
        Mat img = Highgui.imread(getFile(captureScreen()).getAbsolutePath());

        Mat templ = Highgui.imread(templateFile.getAbsolutePath());

        // Create the result matrix
        int result_cols = img.cols() - templ.cols() + 1;
        int result_rows = img.rows() - templ.rows() + 1;
        Mat result = new Mat(result_rows, result_cols, CvType.CV_32FC1);

        // Do the Matching and Normalize
        int match_method = Imgproc.TM_CCOEFF_NORMED;
        Imgproc.matchTemplate(img, templ, result, match_method);

        //Core.normalize(result, result, 0, 1, Core.NORM_MINMAX, -1, new Mat());

        // Localizing the best match with minMaxLoc
        Core.MinMaxLocResult mmr = Core.minMaxLoc(result);

        org.opencv.core.Point matchLoc;
        System.out.println(mmr.maxVal);
        if (match_method == Imgproc.TM_SQDIFF || match_method == Imgproc.TM_SQDIFF_NORMED) {
            matchLoc = mmr.minLoc;
        } else {
            matchLoc = mmr.maxLoc;
        }
        double t;
        if(throughput.get()!=null){
            t = throughput.get();
        }else{
            t = 0.9;
        }
        if(mmr.maxVal>t){
            return new Point(Double.valueOf(matchLoc.x).intValue(), Double.valueOf(matchLoc.y).intValue());
        }
        return null;
    }
    void setThroughput(double throughput) {
        this.throughput.set(throughput);
    }
    public static void main(String[] args) throws AWTException, IOException {
        System.out.println(new ImageMatcher(new Robot()).find(new File("D://template.png")));
    }
}
